//
//  CZContactsViewController.m
//  XMPP项目练习
//
//  Created by 盛 发 况 on 16/5/5.
//  Copyright © 2016年 盛 发 况. All rights reserved.
//

#import "CZContactsViewController.h"
#import "CZXMPPTools.h"
#import "XMPPUserCoreDataStorageObject.h"
#import "CZChatViewController.h"

@interface CZContactsViewController ()<NSFetchedResultsControllerDelegate>
@property (nonatomic, strong) NSFetchedResultsController *fetchedResultsController;

@end

@implementation CZContactsViewController

- (NSFetchedResultsController *)fetchedResultsController {
    if (_fetchedResultsController != nil) {
        return _fetchedResultsController;
    }
    
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"XMPPUserCoreDataStorageObject"];
    // 在线状态
    NSSortDescriptor *sort1 = [NSSortDescriptor sortDescriptorWithKey:@"sectionNum" ascending:YES];
    // 显示的名称
    NSSortDescriptor *sort2 = [NSSortDescriptor sortDescriptorWithKey:@"displayName" ascending:YES];
    request.sortDescriptors = @[sort1, sort2];
    
    // 过滤掉对方没有确认的好友
    request.predicate = [NSPredicate predicateWithFormat:@"!(subscription CONTAINS 'none')"];
    NSManagedObjectContext *ctx = [CZXMPPTools sharedXMPPTools].xmppRosterCoreDataStorage.mainThreadManagedObjectContext;
    
    _fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:ctx sectionNameKeyPath:nil cacheName:nil];
    
    // 设置代理
    _fetchedResultsController.delegate = self;
    
    return _fetchedResultsController;
}

// 绑定数据内容变化，刷新表格
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
    DDLogInfo(@"%s", __FUNCTION__);
    
    [self.tableView reloadData];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 查询数据
    [self.fetchedResultsController performFetch:NULL];
}


// 给目标视图控制器设置数值
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    // 是否是聊天视图控制器
    if ([segue.destinationViewController isKindOfClass:[CZChatViewController class]]) {
        CZChatViewController *vc = segue.destinationViewController;
        
        // 将选中的jid设置给vc，OC中编译之后，都是发送消息，如果方法没有没有参数，同样可以使用.语法
        XMPPUserCoreDataStorageObject *user = [self.fetchedResultsController objectAtIndexPath:self.tableView.indexPathForSelectedRow];
        vc.chatJID = user.jid;
    }

}

#pragma mark --- tableView的数据源及代理
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.fetchedResultsController.fetchedObjects.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *ID = @"ContactCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    
     // 取出对象
    XMPPUserCoreDataStorageObject *user = [self.fetchedResultsController objectAtIndexPath:indexPath];
    DDLogInfo(@"%zd %@ %@ %@", user.section, user.sectionName, user.sectionNum, user.jidStr);
    
        // subscription
        // 如果是none表示对方还没有确认
        // to   我关注对方
        // from 对方关注我
        // both 互粉
    NSString *str = [user.jidStr stringByAppendingFormat:@" | %@",user.subscription];
    
    cell.textLabel.text = str;
    cell.detailTextLabel.text = [self userStatusWithSection:user.section];
    
    return cell;
}

- (NSString *)userStatusWithSection:(NSInteger)section {
    // section
    // 0 在线
    // 1 离开
    // 2 离线
    switch (section) {
        case 0:
            return @"在线";
            break;
        case 1:
            return @"离开";
            break;
        case 2:
            return @"离线";
            break;
        default:
            return @"未知";
            break;
    }
    
}

#pragma mark - 删除好友
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        
        XMPPUserCoreDataStorageObject *user = [self.fetchedResultsController objectAtIndexPath:indexPath];
        XMPPJID *jid = user.jid;
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"是否确定要删除?" preferredStyle: UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            // 直接删除好友，应该提示一下用户
            [[CZXMPPTools sharedXMPPTools].xmppRoster removeUser:jid];
        }]];
        
        [self presentViewController:alert animated:YES completion:nil];
    }
    
}

@end






